<template>
  <el-container v-loading="loading">
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="120px">
        <el-form-item label="直播类型" prop="type">
          <div>
            <el-radio-group v-model="form.model.type">
              <el-radio :label="0">手机直播</el-radio>
              <el-radio :label="1">推流设备直播</el-radio>
            </el-radio-group>
            <div class="desc" v-if="form.model.type === 0">通过“小程序直播”小程序开播</div>
            <div class="desc" v-if="form.model.type === 1"
              >通过第三方推流设备发起直播，请自行定义画面宽高比</div
            >
          </div>
        </el-form-item>
        <!-- <el-form-item label="播放方式" prop="way">
            <div>
              <el-radio-group v-model="form.model.way">
                <el-radio label="column">竖屏</el-radio>
                <el-radio label="row">横屏</el-radio>
              </el-radio-group>
              <div class="desc"
                >横屏：视频宽高比为16:9、4:3、1.85:1 ；竖屏：视频宽高比为9:16、2:3</div
              >
            </div>
          </el-form-item> -->
        <el-form-item label="直播间标题" prop="name">
          <el-input v-model="form.model.name" placeholder="请输入直播间标题"></el-input>
        </el-form-item>
        <el-form-item label="背景图" prop="cover_img">
          <sa-uploader
            v-model="form.model.cover_img"
            fileType="image"
            :filesize="2048"
          ></sa-uploader>
          <div class="desc sa-m-l-12"> 直播间背景图，图片建议像素1080*1920，大小不超过2M </div>
        </el-form-item>
        <el-form-item label="分享图" prop="share_img">
          <sa-uploader
            v-model="form.model.share_img"
            fileType="image"
            :filesize="1024"
          ></sa-uploader>
          <div class="desc sa-m-l-12"> 直播间分享图，图片建议像素800*640，大小不超过1M </div>
        </el-form-item>
        <el-form-item label="封面图" prop="feeds_img">
          <sa-uploader
            v-model="form.model.feeds_img"
            fileType="image"
            :filesize="100"
          ></sa-uploader>
          <div class="desc sa-m-l-12">
            购物直播频道封面图，图片建议像素800*800，大小不超过100KB
          </div>
        </el-form-item>
        <el-form-item label="开播时间" prop="date_time">
          <div>
            <el-date-picker
              v-model="form.model.date_time"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              prefix-icon="Calendar"
              :editable="false"
              :disabled-date="disabledDate"
            />
            <div class="desc">
              开播时间需要在当前时间的30分钟后 并且 开始时间不能在 6 个月后<br />
              开播时间和结束时间间隔不得短于30分钟，不得超过72小时<br />
              直播间在开始时间前也可以开播，并且到结束时间后不会强制结束。<br />
              若到结束时间仍未开播，则直播间无法再开播。
            </div>
          </div>
        </el-form-item>
        <el-form-item label="主播昵称" prop="anchor_name">
          <el-input v-model="form.model.anchor_name" placeholder="请输入主播昵称"></el-input>
        </el-form-item>
        <el-form-item label="主播微信账号" prop="anchor_wechat">
          <div>
            <el-input
              v-model="form.model.anchor_wechat"
              placeholder="请输入主播微信账号"
            ></el-input>
            <div class="desc">
              每个直播间需要绑定一个用作核实主播身份，不会展示给观众。<br />
              主播微信号，如果未实名认证，需要先前往“小程序直播”小程序进行实名验证。
            </div>

            <el-popover :width="180" trigger="click">
              <template #reference>
                <el-button class="is-link" type="primary">小程序认证</el-button>
              </template>
              <img class="qrcode-img" src="/static/images/wechatMplive/live-qrcode.png" />
            </el-popover>
          </div>
        </el-form-item>
        <el-form-item label="主播副号" prop="sub_anchor_wechat">
          <el-input v-model="form.model.sub_anchor_wechat" placeholder="请输入主播副号"></el-input>
        </el-form-item>
        <el-form-item label="官方收录">
          <div>
            <el-switch
              v-model="form.model.is_feeds_public"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
            <div class="desc">
              开启后本场直播将有可能被官方推荐。<br />
              此项设置在直播间创建完成后可以在控制台内修改。
            </div>
          </div>
        </el-form-item>

        <el-form-item label="允许点赞">
          <el-radio-group v-model="form.model.close_like">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="展示商品货架">
          <el-radio-group v-model="form.model.close_goods">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="允许评论">
          <el-radio-group v-model="form.model.close_comment">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="允许回放">
          <el-radio-group v-model="form.model.close_replay">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="打开客服">
          <el-radio-group v-model="form.model.close_kf">
            <el-radio :label="0">开启</el-radio>
            <el-radio :label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button
        v-if="modal.params.type == 'add'"
        v-auth="'shop.admin.app.mplive.room.add'"
        type="primary"
        @click="confirm"
        >保存</el-button
      >
      <el-button
        v-if="modal.params.type == 'edit'"
        v-auth="'shop.admin.app.mplive.room.edit'"
        type="primary"
        @click="confirm"
        >更新</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../../app.service';
  import { cloneDeep } from 'lodash';
  import dayjs from 'dayjs';
  const emit = defineEmits(['modalCallBack']);
  const props = defineProps({
    modal: {
      type: Object,
    },
  });
  // 添加 编辑 form
  let formRef = ref(null);
  const form = reactive({
    model: {
      way: 'column',
      type: 0,
      name: '',
      date_time: '',
      anchor_name: '',
      anchor_wechat: '',
      sub_anchor_wechat: '',
      is_feeds_public: 1,
      close_kf: 0,
      close_replay: 0,
      close_comment: 0,
      close_goods: 0,
      close_like: 0,
      feeds_img: '',
      share_img: '',
      cover_img: '',
    },
    rules: {
      type: [{ required: true, message: '请选择直播类型', trigger: 'change' }],
      way: [{ required: true, message: '请选择播放方式', trigger: 'change' }],
      feeds_img: [{ required: true, message: '请选择封面图', trigger: 'change' }],
      share_img: [{ required: true, message: '请选择分享图', trigger: 'change' }],
      cover_img: [{ required: true, message: '请选择背景图', trigger: 'change' }],
      date_time: [{ required: true, message: '请选择开播时间', trigger: 'change' }],
      name: [{ validator: checkTitle, trigger: 'change' }],
      anchor_name: [{ validator: checkNickname, trigger: 'change' }],
      anchor_wechat: [{ required: true, message: '请输入主播微信账号', trigger: 'blur' }],
    },
  });
  const loading = ref(false);
  //获取默认开始时间为当前时间后40分钟
  const defaultTime = ref([
    new Date(new Date().getTime() + 40 * 60 * 1000),
    new Date(2000, 2, 1, 23, 59, 59),
  ]);
  // 获取详情
  async function getDetail(id) {
    loading.value = true;
    const { error, data } = await api.mplive.room.detail(id);
    if (error === 0) {
      form.model = data;
      form.model.date_time = [
        dayjs(data.start_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
        dayjs(data.end_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
      ];
    }
    loading.value = false;
  }
  // 禁止时间
  function disabledDate(time) {
    return time.getTime() < Date.now() - 86400000;
  }
  // 表单关闭时提交
  async function confirm() {
    // 表单验证
    unref(formRef).validate(async (valid) => {
      if (!valid) return;
      loading.value = true;
      let submitForm = cloneDeep(form.model);
      submitForm.start_time = Number(new Date(form.model.date_time[0]).getTime() / 1000);
      submitForm.end_time = Number(new Date(form.model.date_time[1]).getTime() / 1000);
      delete submitForm.date_time;
      const { error } =
        props.modal.params.type == 'add'
          ? await api.mplive.room.add(submitForm)
          : await api.mplive.room.edit(props.modal.params.id, submitForm);
      if (error == 0) {
        emit('modalCallBack', { event: 'confirm' });
      }
      loading.value = false;
    });
  }
  function checkTitle(rule, value, callback) {
    if (!value) {
      return callback(new Error('请输入直播间标题'));
    }
    const length =
      value.match(/[^ -~]/g) == null ? value.length : value.length + value.match(/[^ -~]/g).length;
    if (length < 6 || length > 34) {
      callback(new Error('直播标题必须为3-17个字（一个字等于两个英文字符或特殊字符）'));
    } else {
      callback();
    }
  }
  function checkNickname(rule, value, callback) {
    if (!value) {
      return callback(new Error('请输入主播昵称'));
    }
    const length =
      value.match(/[^ -~]/g) == null ? value.length : value.length + value.match(/[^ -~]/g).length;
    if (length < 4 || length > 30) {
      callback(new Error('直播标题必须为2-15个字（一个字等于两个英文字符或特殊字符）'));
    } else {
      callback();
    }
  }
  async function init() {
    if (props.modal.params.id) {
      await getDetail(props.modal.params.id);
    }
  }

  onMounted(() => {
    init();
  });
</script>
<style lang="scss" scoped>
  .desc {
    font-weight: normal;
    font-size: 12px;
    line-height: 18px;
    color: var(--sa-subfont);
  }

  .qrcode-img {
    width: 150px;
    height: 150px;
  }
</style>
